/*
 * display.c
 *
 *  Created on: 2011/06/17
 *      Author: AKS
 */

#include "core/include/aks_processor.h"
#include "core/include/process.h"
#include "core/include/types.h"
#include "core/include/aks_string.h"

#include "app/tinySystem/include/tinySystem.h"
#include "app/frame_buffer/include/frame_buffer.h"
#include "app/frame_buffer/include/display_tsk.h"
#include "app/frame_buffer/include/camera_tsk.h"

#include "app/cv/include/aksImage.h"
#include "app/cv/include/aksDraw.h"

#include "app/prompt/include/prompt_tsk.h"

DWORD display_base_adr;
static BYTE  current_buffer_index;

PROCESS display_process =
{
	display_tsk,
    NULL,
    display_tsk_wakeup,
    NULL,
    0
};

LIST_ITEM displayItm
=
{
    NULL,
    &display_process
};

/* for display usage */
AksImage *currentImage;
static AksImage display_buffer1;
static AksImage display_buffer2;

void display_tsk(void *param)
{
	// UART_transmitString(UART_DBG, (BYTE *)"display task is activated \r\n");

	// draw image from camera to LCD
	camera_drawToImage(currentImage, aksPoint(0,0));

	// draw prompt
	draw_prompot(9, 9, currentImage);

	// switch frame buffer
	current_buffer_index = 0x01 & (current_buffer_index ^ 0x01);
	frame_buffer_switched(display_base_adr, current_buffer_index);

    sleepCurrentProcess(display_tsk_wakeup, NULL);
}


BOOL display_tsk_wakeup(void *param)
{
    if(frame_buffer_switched(display_base_adr, current_buffer_index) && camera_image_ready_flag == TRUE)
    {
        return TRUE;
    }
    else
    {
    	return FALSE;
    }
}

BOOL init_display_tsk(BYTE SS_index)
{
	/* initialize frame buffer */
	display_base_adr = ((DWORD)(SS_index) << 21) & 0xE00000;
	current_buffer_index = 0;

	BYTE str[100];
	BYTE *next = str;

    next = write_Str((BYTE*)"display_base_adr = 0x", next, 100 );
    next = writeUHex( display_base_adr, next, 100 );
    next = write_Str((BYTE*)"\r\n", next, 100 );

    UART_transmitString(UART_DBG, str);

	init_frame_buffer(display_base_adr);
    while(!frame_buffer_switched(display_base_adr, current_buffer_index));

    UART_transmitString(UART_DBG, (BYTE *)"Frame Buffer for LCD is initialized. \r\n");

    createImage(320, 240, display_base_adr, &display_buffer1, AKS_BGR, aksPoint(0,0));
    aksSetZero(&display_buffer1);
    while(!frame_buffer_switched(display_base_adr, 1));

    createImage(320, 240, display_base_adr, &display_buffer2, AKS_BGR, aksPoint(0,0));
    aksSetZero(&display_buffer2);
    while(!frame_buffer_switched(display_base_adr, 0));

    currentImage = &display_buffer1;

    return TRUE;
}
